/**
 * desc：
 * author：王文军
 * date：  2023/1/28 11:42
 */
(function () {
  // EPG API 移除focus
  var isFrame = parent !== self;
  window.prompt = function () { }
  if (isFrame) {
    window.Authentication = parent.Authentication
  }
  else {
    window.Authentication = {
      CTCSetConfig: function (key, valu) {
        localStorage.setItem(key, valu) || "";
        sessionStorage.setItem(key, valu) || "";
        return
      },
      CTCGetConfig: function (key) {
        localStorage.getItem(key) || "";
        return sessionStorage.getItem(key) || "";
      },
      CUGetConfig: function (key) {
        localStorage.getItem(key) || "";
        return sessionStorage.getItem(key) || "";
      },
      CUSetConfig: function (key, valu) {
        localStorage.setItem(key, valu) || "";
        sessionStorage.setItem(key, valu) || "";
        return
      }
    };
  }
  var _eventStr = ""
  var _playEvent = new KeyboardEvent('keydown', {
    keyCode: 768,     // 对应 ASCII 码的 'A'
    key: 'MediaPlayer',        // 触发的按键
    endKey: true,   // 是否按下 Ctrl 键
    altKey: false,   // 是否按下 Alt 键
    shiftKey: false, // 是否按下 Shift 键
    metaKey: false   // 是否按下 Meta 键
  });
  window.MediaPlayer = function () {
    this.nativePlayerInstanceID = 1;
    this.log = function () {
      parent.console.log('########### chrome');
    }
    this.totalTime = 3600;
    this.currentTime = 0;
    this.playInterval = null;
    this.joinChannel = function (chan, PID) {
      this.currentTime = 0;
      _eventStr = JSON.stringify({
        entry_id: "jsonentry1",
        playStatus: "live",
        instance_id: 0,
        media_code: "532685543,532685266,532686018,0,0,true",
        type: "EVENT_MEDIA_BEGINING"
      })
      document.dispatchEvent(_playEvent);
    };
    this.getNativePlayerInstanceID = function () {
      return this.nativePlayerInstanceID
    };
    this.setVolume = function (volum) { };
    this.setAudioVolumeUIFlag = function (flag) { };
    this.resume = function () {
      clearInterval(this.playInterval);
      this.playInterval = setInterval(() => {
        if (this.currentTime >= 5400) {
          this.currentTime = 0;
        }
        this.currentTime += 1;
      }, 1000)
    };
    this.stop = function () {
      if (!_eventStr.playStatus || _eventStr.playStatus !== "stop") {
        _eventStr = JSON.stringify({
          entry_id: "jsonentry1",
          playStatus: "stop",
          instance_id: 0,
          media_code: "532685543,532685266,532686018,0,0,true",
          type: "EVENT_PLAYMODE_CHANGE"
        })
        document.dispatchEvent(_playEvent);
      }

      this.currentTime = 0;
      clearInterval(this.playInterval);
    };
    this.gotoEnd = function () { };
    this.leaveChannel = function () { };
    this.getChannelNum = function () { };
    this.getMediaDuration = function () {
      return this.totalTime;
    };
    this.setMuteFlag = function (mute) { };
    this.setSingleMedia = function (mediaStr) {
      this.currentTime = 0;
      _eventStr = JSON.stringify({
        entry_id: "jsonentry1",
        playStatus: "play",
        instance_id: 0,
        media_code: "532685543,532685266,532686018,0,0,true",
        type: "EVENT_MEDIA_BEGINING"
      })
      document.dispatchEvent(_playEvent);
    };
    this.setNativeUIFlag = function (flag) { };
    this.selectAudio = function () { };
    this.playByTime = function (type, point) {
      clearInterval(this.playInterval);
      this.currentTime = point
      this.playInterval = setInterval(() => {
        if (this.currentTime >= 5400) {
          this.currentTime = 0;
        }
        this.currentTime += 1;
      }, 1000)
    };
    this.refreshVideoDisplay = function () { };
    this.setVideoDisplayMode = function (isFull) { };
    this.setVideoDisplayArea = function () { };
    this.setSingleOrPlaylistMode = function () { };
    this.getCurrentPlayTime = function () {
      if (this.currentTime == this.totalTime) {
        _eventStr = JSON.stringify({
          entry_id: "jsonentry1",
          playStatus: "end",
          instance_id: 0,
          media_code: "530822718,530822837,530833395,0,0,true",
          type: "EVENT_MEDIA_END"
        })
        document.dispatchEvent(_playEvent);
        this.currentTime = 0
        return this.totalTime
      }
      return this.currentTime;
    };
    this.getAllAudioTrackInfo = function () { };
    this.releaseMediaPlayer = function () {
      this.nativePlayerInstanceID = 0;
      clearInterval(this.playInterval);
    };
    this.pause = function () {
      clearInterval(this.playInterval);
    };
    this.clearScreen = function () { };
    this.getPlaybackMode = function () { };
    this.getVolume = function () {
      return 20
    };
    this.getMuteFlag = function () { };
    this.setMuteUIFlag = function (n) { };
    this.getAudioVolumeUIFlag = function () { };
    this.getNativeUIFlag = function () { };
    this.getMuteUIFlag = function () { };
    this.setAudioTrackUIFlag = function (n) { };
    this.getVideoDisplayHeight = function () { };
    this.setProgressBarUIFlag = function (n) { };
    this.setChannelNoUIFlag = function (n) { };
    this.setAllowTrickmodeFlag = function (n) { };
    this.setCycleFlag = function (n) { };
    this.getVideoDisplayWidth = function (n) { };
    this.playFromStart = function (n) {
      clearInterval(this.playInterval);
      this.playInterval = setInterval(() => {
        if (this.currentTime >= 5400) {
          this.currentTime = 0;
        }
        this.currentTime += 1;
      }, 1000)
    };
    this.initMediaPlayer = function (
      instanceId,
      playListFlag,
      videoDisplayMode,
      height,
      width,
      left,
      top1,
      muteFlag,
      useNativeUIFlag,
      subtitleFlag,
      videoAlpha,
      cycleFlag,
      randomFlag,
      autoDelFlag
    ) { };
    this.set = function (type, value) { };
  };
  window.WR = function () { }
  window.WR_Media_AV = {
    play: function () { },
    getDuration: function () { return 0 },
    pause: function () { },
    stop: function () { },
    seek: function () { },
    setFullScreen: function () { },
    getElapsed: function () { return 60 * 1000 * 60 },
  }
  window.Utility = {
    getEvent: function () {
      return _eventStr
    }
  }
  window.STBAppManager = {
    isAppInstalled: function (appName) {
      return window.Authentication.CTCGetConfig("pcapk").indexOf(appName) > -1;
    },
    getAppVersion: function (appName) {
      return window.Authentication.CTCGetConfig(appName) || false;
    },
    installApp: function (apk) {
      var data = window.Authentication.CTCGetConfig("pcapk");
      data = data.split(",").filter(e => e);
      data.push(apk);
      console.log(data)
      window.Authentication.CTCSetConfig("pcapk", data.join(","))
    },
    startAppByIntent: function (str) {
      var todesc = JSON.parse(str);
      if (todesc.extra) {
        var a = todesc.extra.filter(i => i.name == "pageUrl");
        if (a && a[0]) {
          parent.window.location.href = a[0].value
        }
      }
    },
    uninstallApp: function (apk) {
      var data = window.Authentication.CTCGetConfig("pcapk");
      data = data.replace(apk + ",", "").replace(apk, "");
      console.log(data)
      window.Authentication.CTCSetConfig("pcapk", data)
    },
  };
  setTimeout(function () {
    if (!isFrame) window.removeEventListener("focus", window.getEventListeners("focus") && window.getEventListeners("focus")[0].listener)
  }, 1000)
  window._addEventListener = window.addEventListener;
  window._removeEventListener = window.removeEventListener;
  window.hookeventListenerList = {}
  window.addEventListener = function (type, listener, useCapture = false) {
    this._addEventListener(type, listener, useCapture);
    if (!window.hookeventListenerList) window.hookeventListenerList = {};
    if (!window.hookeventListenerList[type]) window.hookeventListenerList[type] = [];
    window.hookeventListenerList[type].push({ type, listener, useCapture });
  };
  window.removeEventListener = function (type, listener, useCapture = false) {
    this._removeEventListener(type, listener, useCapture);
    if (!window.hookeventListenerList) window.hookeventListenerList = {};
    if (!window.hookeventListenerList[type]) window.hookeventListenerList[type] = [];
    for (let i = 0; i < window.hookeventListenerList[type].length; i++) {
      if (window.hookeventListenerList[type][i].listener === listener && window.hookeventListenerList[type][i].useCapture === useCapture) {
        window.hookeventListenerList[type].splice(i, 1);
        break;
      }
    }
    if (window.hookeventListenerList[type].length == 0) delete window.hookeventListenerList[type];
  };
  window.getEventListeners = function (type) {
    if (!window.hookeventListenerList) window.hookeventListenerList = {};
    if (type === undefined) return window.hookeventListenerList;
    return window.hookeventListenerList[type];
  };
  (function (xhr) {
    var XHR = XMLHttpRequest.prototype;
    var open = XHR.open;
    var send = XHR.send;
    var intercept = false;
    XHR.open = function () {
      if (
        (arguments[1].indexOf('websocketservice/socket.io') > -1) ||
        (arguments[1].indexOf('postkeyword') > -1) ||
        (arguments[1].indexOf('syncchannelinfo') > -1) ||
        (arguments[1].indexOf('syncclientinfo') > -1) ||
        (arguments[1].indexOf('getcmd') > -1) ||
        (arguments[1].indexOf('xhr-polling-batch') > -1)
      ) {
        intercept = true
      }
      return open.apply(this, arguments);
    }
    XHR.send = function (postData) {
      if (intercept) {
        return intercept = false
      }
      if(postData&&postData.indexOf&&(postData.indexOf(`com.iflytek.xiri.videoPlayScene","_commands"`)>-1)){
        return;
      }
      return send.apply(this, arguments);
    };
  })(XMLHttpRequest);
  window.localStorage.setItem("isPC", "1"); // 新增PC的判断
  window.sessionStorage.setItem("isPC", "1"); // 新增PC的判断
  document.addEventListener('DOMContentLoaded', function () {
    console.log('vue-chrome扩展已载入');
    insertFloat();
  });
// 在target页面中新建一个带有id的dom元素，将vue对象挂载到这个dom上。
  function insertFloat() {
    const _body = document.getElementsByTagName("html")[0];
    let element = document.createElement('div');
    let attr = document.createAttribute('id');
    attr.value = 'appPlugin';
    element.setAttributeNode(attr);
    // document.getElementsByTagName('body')[0].appendChild(element);
    if (document.body.tagName === "FRAMESET") {
      _body.appendChild(element);
    } else {
      (document.body || _body || document.documentElement).appendChild(element);
    }
    // let link = document.createElement('link');
    // let linkAttr = document.createAttribute('rel');
    // linkAttr.value = 'stylesheet';
    // let linkHref = document.createAttribute('href');
    // linkHref.value = 'https://unpkg.com/element-ui/lib/theme-chalk/index.css';
    // link.setAttributeNode(linkAttr);
    // link.setAttributeNode(linkHref);
    // document.getElementsByTagName('head')[0].appendChild(link);

    let left = 0;
    let top = 0;
    let mx = 0;
    let my = 0;
    let onDrag = false;

    var drag = {
      inserted: function (el) {
        (el.onmousedown = function (e) {
          left = el.offsetLeft;
          top = el.offsetTop;
          mx = e.clientX;
          my = e.clientY;
          if (my - top > 40) return;

          onDrag = true;
        }),
          (window.onmousemove = function (e) {
            if (onDrag) {
              let nx = e.clientX - mx + left;
              let ny = e.clientY - my + top;
              let width = el.clientWidth;
              let height = el.clientHeight;
              let bodyWidth = window.document.body.clientWidth;
              let bodyHeight = window.document.body.clientHeight;

              if (nx < 0) nx = 0;
              if (ny < 0) ny = 0;

              if (ny > bodyHeight - height && bodyHeight - height > 0) {
                ny = bodyHeight - height;
              }

              if (nx > bodyWidth - width) {
                nx = bodyWidth - width;
              }

              el.style.left = nx + 'px';
              el.style.top = ny + 'px';
            }
          }),
          (el.onmouseup = function (e) {
            if (onDrag) {
              onDrag = false;
            }
          });
      },
    };

  }
})();
